package until;


import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class XMLParser {

	private File xmlfile;
	public String file;
	
	private SAXBuilder buider;
	private Document doc;
	private Element rootnode;
	
	public XMLParser(String configUrl){
		file=configUrl;
		xmlfile= new File(configUrl);
		try {
			buider= new SAXBuilder();
			doc=(Document)buider.build(xmlfile);
			rootnode=doc.getRootElement();
		} catch (IOException e) {
			
			// TODO: handle exception
			System.out.println(e.getMessage());
		}
		catch (JDOMException e) {
			// TODO: handle exception
		System.out.println(e.getMessage());
		}
		
	}
	public Element getRootNode(){
		return rootnode;
		
	}
	public String readRootNode(String strElement){
		String result="";
		String[] arrelementpath= new String[2];
		arrelementpath=strElement.split("\\|");
		String funtiontagName=arrelementpath[0];
		String taggetelement=arrelementpath[1];
	    List<Element> list=rootnode.getChildren(funtiontagName);
	    
		//Function tag is available
		if(list.size() > 0) {
			Element functionNode = list.get(0);
			list = functionNode.getChildren(taggetelement);
			
			if(list.size() > 0) {
				result = list.get(0).getValue();
			}
		}
		return result;
		
	}
	
	public String readNodeByname(String nodeName){
		String nodeValue="";
		List<Element> list= rootnode.getChildren("menu");
		if(list.size()>0){
			Element rootConfig=list.get(0);
			list=rootConfig.getChildren(nodeName);
			if(list.size()>0){
				Element node=list.get(0);
				nodeValue=node.getValue();
				
			}
		}
		return nodeValue;
	}
	//Read node by name
		public String readNode (String nodeName) {
					
			String nodeValue = "";
			
			//Browse for target node
			List<Element> list = rootnode.getChildren("config");
			
			//Node is available
			if(list.size() > 0) {
				Element configRoot = list.get(0);
				list = configRoot.getChildren(nodeName);
				if(list.size() > 0) {
					Element node = list.get(0);
					nodeValue = node.getValue();
				}
			}
			
			return nodeValue;
		}
}
